import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:geolocator/geolocator.dart';

void main() {
  runApp(WeatherApp());
}

class WeatherApp extends StatelessWidget {
  const WeatherApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: WeatherHomePage(),
    );
  }
}

class WeatherHomePage extends StatefulWidget {
  const WeatherHomePage({super.key});

  @override
  _WeatherHomePageState createState() => _WeatherHomePageState();
}

class _WeatherHomePageState extends State<WeatherHomePage> {
  String apiKey = 'fef221ec6756d48ef533e3309bcfe2ba'; // 你的 OpenWeather API Key
  String city = "Beijing";
  Map<String, dynamic>? weatherData;
  TextEditingController cityController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _fetchWeather(city);
  }

  Future<void> _fetchWeather(String city) async {
    final url = Uri.parse(
      'https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric',
    );
    try {
      final response = await http.get(url);
      if (response.statusCode == 200) {
        setState(() {
          weatherData = json.decode(response.body);
        });
      } else {
        _showError("无法获取天气数据");
      }
    } catch (e) {
      _showError("请求失败，请检查网络连接");
    }
  }

  Future<void> _getCurrentLocationWeather() async {
    try {
      Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high,
      );
      final url = Uri.parse(
        'https://api.openweathermap.org/data/2.5/weather?lat=${position.latitude}&lon=${position.longitude}&appid=$apiKey&units=metric',
      );
      final response = await http.get(url);
      if (response.statusCode == 200) {
        setState(() {
          weatherData = json.decode(response.body);
        });
      } else {
        _showError("无法获取当前位置天气");
      }
    } catch (e) {
      _showError("获取位置失败，请检查权限");
    }
  }

  void _showError(String message) {
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(SnackBar(content: Text(message)));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("天气查询 App"),
        actions: [
          IconButton(
            icon: Icon(Icons.location_on),
            onPressed: _getCurrentLocationWeather,
          ),
        ],
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: cityController,
              decoration: InputDecoration(
                labelText: "输入城市名称",
                suffixIcon: IconButton(
                  icon: Icon(Icons.search),
                  onPressed: () {
                    if (cityController.text.isNotEmpty) {
                      _fetchWeather(cityController.text);
                    }
                  },
                ),
              ),
            ),
            SizedBox(height: 20),
            weatherData == null
                ? Center(child: CircularProgressIndicator())
                : Column(
                  children: [
                    Text(
                      "${weatherData!["name"]}",
                      style: TextStyle(
                        fontSize: 30,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      "${weatherData!["weather"][0]["description"]}",
                      style: TextStyle(fontSize: 20),
                    ),
                    Text(
                      "温度: ${weatherData!["main"]["temp"]}°C",
                      style: TextStyle(fontSize: 24),
                    ),
                    Text(
                      "湿度: ${weatherData!["main"]["humidity"]}%",
                      style: TextStyle(fontSize: 20),
                    ),
                    Text(
                      "风速: ${weatherData!["wind"]["speed"]} m/s",
                      style: TextStyle(fontSize: 20),
                    ),
                    SizedBox(height: 20),
                    ElevatedButton(
                      onPressed: _getCurrentLocationWeather,
                      child: Text("获取当前位置天气"),
                    ),
                  ],
                ),
          ],
        ),
      ),
    );
  }
}
